<?php
	/**
	 * 商品分类管理控制器
	 */
	class CategoryAction extends CommonAction{
		//商品分类列表视图
		public function index(){
			import('ORG.Util.Page');
			$db = M('category');
			//计算分页
			$count = $db->count('id');
			$page = new Page($count, 60);
			$limit = $page->firstRow .',' . $page->listRows;
			$result = $db->limit($limit)->select();
			//分配置变量
			$category = recursion($result , 0 , 3);//调用无限级分类格式化
			$this->category = $category;
			$this->page = $page->show();
			$this->display();
		}
		//添加商品分类视图
		public function addCategory(){
			$db = M("type");
			$type = $db->field('id,name')->select();
			$cate = $db->table("hd_category")->field('id,name,tid,pid')->select();
			$this->cate = recursion($cate , 0 ,1);
			$this->type = $type;
			$this->display();
		}

		//添加商品分类数据到数据库
		public function runAddCategory(){
			$pid = $this->_post('pid');
			if($pid>0){
				$result = M("category")->where("id='".$pid."'")->field("tid")->find();
				$tid = $result['tid'];
			}else{
				$tid = $this->_post('type');
			}
			$data = array(
				'name' => $this->_post('catename'),
				'pid' => $this->_post('pid'),
				'tid' => $tid,
				'description' => $this->_post('description')
				);
			$db = M("category");
			if($db->data($data)->add()){
				$this->success("添加商品分类成功！",U('index'));
			}else{
				$this->error("添加商品分类失败，请重试！");
			}
		}

		//编辑商品分类
		public function editCategory(){
			$cid = $this->_get('cid','intval');
			$db = M('category');
			$editCate = $db->where("id='".$cid."'")->find();
			$allCate = $db->where('pid<'.$editCate['pid'])->select();
			// $parentCate = recursion($allCate , $editCate['pid'] , 2 );//查找其所有的父类
			//分配该分类的所有父类到视图
			$this->parentCate = recursion($allCate , 0 ,1);
			//分配所有的商品类型到视图
			$type = $db->table("hd_type")->select();
			$this->type = $type;
			//分配要编辑的商品分类信息到视图
			$this->editCate = $editCate;
			$this->display();
		}

		//处理编辑的商品分类数据
		public function runEditCategory(){
			$data = array(
				'name' => $this->_post('catename'),
				'pid' =>$this->_post('pid' , 'intval'),
				'type' =>$this->_post('type'),
				'description' =>$this->_post('description')
				);
			$db = M('category');
			if($db->where('id='.$this->_post('cid','intval'))->save($data)){
				$this->success('编辑商品分类数据成功！',U('index'));
			}else{
				$this->error('编辑商品分类数据失败，请重试！');
			}
		}

		//异步删除商品分类数据
		public function delCategory(){
			$cid = $this->_get('cid');
			$db = M("category");
			$category = $db->where('id='.$cid)->find();
			$haveChild = $db->where('pid='.$cid)->find();
			$data = array();
			if(is_array($haveChild)){
				$data['state'] = 'error';
				$data['msg'] = '请先删除子商品分类！';
			}else{
				if($db->delete($cid)){
					$data['state'] = 'success';
					$data['msg'] = '删除商品分类数据成功！';
				}else{
					$data['state'] = 'error';
					$data['msg'] = '删除商品分类数据失败！';
				}
			}
			echo json_encode($data);
		}
	}
?>